/*
 * usb_com.c
 *
 *  Created on: 2021年4月10日
 *      Author: legen
 */

#include "usbd_cdc_if.h"
#include "rgb_matrix_led.h"
#include "systick.h"

uint8_t rx_buf[3][APP_RX_DATA_SIZE]; // 多一个防止溢出
uint32_t rx_len[2] = {0};

void usb_com_rx(uint8_t* Buf, uint32_t Len)
{
	if(rx_len[0] == 0)
	{
		memcpy(&rx_buf[0], Buf, Len);
		rx_len[0] = Len;
	}
	else if((rx_len[1]+Len)<(APP_RX_DATA_SIZE*2))
	{
		memcpy(&rx_buf[1][rx_len[1]], Buf, Len);
		rx_len[1] += Len;
	}
}
void usb_com_tx(uint8_t* Buf, uint32_t Len)
{
	uint8_t* txPtr = Buf;
	while(Len > 64)
	{
		CDC_Transmit_FS(txPtr, 64);
		//osDelay(1);
		Len -= 64;
		txPtr += 64;
	}
	CDC_Transmit_FS(txPtr, Len);
	//osDelay(1);
}

static char isUsbConnect = 0;

void usb_process_buf(uint8_t* Buf, uint32_t Len)
{
	char strBuf[200];
	int value1;
	strBuf[0] = '\0';
	Buf[Len]='\0';

	isUsbConnect = 1;

	if(sscanf(Buf, "RedDis %d", &value1) == 1)
	{
		RedDis(value1);
		sprintf(strBuf, "RedDis(%d)\n", value1);
	}
	else if(sscanf(Buf, "BlueDis %d", &value1) == 1)
	{
		BlueDis(value1);
		sprintf(strBuf, "BlueDis(%d)\n", value1);
	}
	else if(sscanf(Buf, "GreenDis %d", &value1) == 1)
	{
		GreenDis(value1);
		sprintf(strBuf, "GreenDis(%d)\n", value1);
	}
	else if(sscanf(Buf, "BlackDis %d", &value1) == 1)
	{
		BlackDis(value1);
		sprintf(strBuf, "BlackDis(%d)\n", value1);
	}
	else
	{
		sprintf(strBuf, "unknow(%s)\n", Buf);
	}
	usb_com_tx(strBuf, strlen(strBuf));
}

int freq = 0;

void freq_task(void)
{
	static u32 startTime = 0;
	char strBuf[200];

	if(isSysTickTimeout(startTime, 1000))
	{
		startTime = GetSysTick();


		if(isUsbConnect)
		{
			sprintf(strBuf, "led freq = %d\n", freq);
			usb_com_tx(strBuf, strlen(strBuf));
		}

		freq = 0;
	}
}

void breathing_light_task(void)
{

}

void usb_task(void)
{
	if(rx_len[0]>0)
	{
		usb_process_buf(rx_buf[0], rx_len[0]);
		rx_len[0] = 0;
	}
	else if(rx_len[1]>0)
	{
		usb_process_buf(rx_buf[1], rx_len[1]);
		rx_len[1] = 0;
	}
	else
	{
		rgb_matrix_led_task();
		freq++;
		//osDelay(1);
	}
	freq_task();

}
